package com.novel.utils;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConverterUtil {

    private static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = null;
            try {
                srcValue = src.getPropertyValue(pd.getName());
            } catch (Exception e) {
                continue;
            }
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        src = null;
        pds = null;
        return emptyNames.toArray(result);
    }

    /**
     * 基于spring的排除null参数的copy
     *
     * @param src    源
     * @param target 指向
     */
    public static void copyPropertiesIgnoreNull(Object src, Object target) {

        org.springframework.beans.BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

    /**
     * 数据类型转换方法
     *
     * @param converters 需要转换的list
     * @return 结果list
     */
    public static <E> List<E> convertList(List<? extends BeanConverter> converters) {
        if (ObjectUtils.isEmpty(converters)) {
            return null;
        }
        List<E> list = new ArrayList<>(converters.size());
        for (BeanConverter converter : converters) {
            list.add((E) converter.doForward());
        }
        return list;
    }

}
